<template>
  <div class="schedule-container">
    <div class="schedule-header">
      <h3>日程管理</h3>
      <el-button type="primary" @click="showAddEventDialog">添加日程</el-button>
    </div>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-calendar v-model="currentDate">
          <template #dateCell="{ data }">
            <div class="calendar-cell">
              <span>{{ data.day.split('-').slice(-1)[0] }}</span>
              <div class="event-dot" v-if="hasEvents(data.day)"></div>
            </div>
          </template>
        </el-calendar>
      </el-col>
      <el-col :span="18">
        <div class="events-list">
          <h4>{{ formatDate(currentDate, 'display') }}的日程</h4>
          <el-empty v-if="currentDateEvents.length === 0" description="当天暂无日程安排" />
          <el-timeline v-else>
            <el-timeline-item
              v-for="event in currentDateEvents"
              :key="event.id"
              :type="event.type"
              :timestamp="event.time"
            >
              <el-card>
                <template #header>
                  <div class="event-header">
                    <span>{{ event.title }}</span>
                    <div>
                      <el-button 
                        type="primary" 
                        link 
                        @click="editEvent(event)"
                      >
                        编辑
                      </el-button>
                      <el-button 
                        type="danger" 
                        link 
                        @click="deleteEvent(event)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </template>
                <p>{{ event.description }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑日程' : '添加日程'"
      width="40%"
    >
      <el-form :model="eventForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="eventForm.title" placeholder="请输入日程标题"></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="eventForm.date"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="时间">
          <el-time-picker
            v-model="eventForm.timeValue"
            format="HH:mm"
            placeholder="选择时间"
            @change="updateTimeString"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="eventForm.type">
            <el-option label="工作" value="primary" />
            <el-option label="个人" value="success" />
            <el-option label="重要" value="danger" />
            <el-option label="信息" value="info" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            placeholder="请输入日程描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEvent">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useScheduleStore } from '@/store/schedule'
import { storeToRefs } from 'pinia'
import { scheduleApi } from '@/utils/api'

const userId = ref(1) // 从登录后的存储中获取，这里先写死
const currentDate = ref(new Date().toISOString().split('T')[0])
const scheduleStore = useScheduleStore()
const { events } = storeToRefs(scheduleStore)
const dialogVisible = ref(false)
const isEdit = ref(false)
const selectedScheduleId = ref(null)
const schedules = ref([])
const isLoading = ref(false)
const showAddDialog = ref(false)

const eventForm = ref({
  title: '',
  date: currentDate.value,
  time: '09:00',
  timeValue: '',
  type: 'work',
  description: '',
  points: 10
})

// 类型选项
const typeOptions = [
  { value: 'work', label: '工作' },
  { value: 'study', label: '学习' },
  { value: 'personal', label: '个人' },
  { value: 'social', label: '社交' }
]

// 积分选项
const pointsOptions = [5, 10, 15, 20, 25, 30]

onMounted(async () => {
  console.log('日程组件加载中...')
  try {
    await loadSchedules()
    console.log('日程数据加载完成，事件数量:', events.value.length)
  } catch (error) {
    console.error('加载日程数据失败:', error)
  }
})

// 获取当前日期的事件
const currentDateEvents = computed(() => {
  const dateStr = formatDate(currentDate.value)
  console.log('当前选中日期:', dateStr)
  console.log('所有事件:', events.value)
  
  const filtered = events.value.filter(event => {
    const eventDate = formatDate(new Date(event.date))
    console.log(`比较: 事件日期 ${eventDate} 与 当前日期 ${dateStr}`)
    return eventDate === dateStr
  })
  
  console.log('过滤后事件:', filtered)
  return filtered
})

// 检查指定日期是否有事件
const hasEvents = (day) => {
  const dateStr = day // YYYY-MM-DD 格式
  return events.value.some(event => {
    const eventDate = formatDate(new Date(event.date))
    return eventDate === dateStr
  })
}

// 日期格式化
const formatDate = (date, type = 'default') => {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  
  if (type === 'display') {
    return `${year}年${month}月${day}日`
  }
  
  return `${year}-${month}-${day}`
}

// 加载日程数据
const loadSchedules = async () => {
  isLoading.value = true
  try {
    // 调用后端API获取数据
    const response = await scheduleApi.getSchedulesByDate(userId.value, currentDate.value)
    schedules.value = response || []
  } catch (error) {
    console.error('加载日程失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 添加日程
const saveEvent = async () => {
  try {
    if (isEdit.value && selectedScheduleId.value) {
      // 更新日程
      await scheduleApi.updateSchedule(selectedScheduleId.value, eventForm.value)
    } else {
      // 创建新日程
      await scheduleApi.createSchedule(userId.value, eventForm.value)
    }
    
    closeDialog()
    loadSchedules()
  } catch (error) {
    console.error('保存日程失败:', error)
  }
}

// 切换日程完成状态
const toggleComplete = async (id) => {
  try {
    await scheduleApi.completeSchedule(id)
    loadSchedules()
  } catch (error) {
    console.error('更新日程状态失败:', error)
  }
}

// 编辑日程
const editEvent = async (id) => {
  try {
    const schedule = await scheduleApi.getScheduleById(id)
    eventForm.value = {
      title: schedule.title,
      date: schedule.date,
      time: schedule.time,
      description: schedule.description,
      type: schedule.type,
      points: schedule.points
    }
    
    isEdit.value = true
    selectedScheduleId.value = id
    showAddDialog.value = true
  } catch (error) {
    console.error('获取日程详情失败:', error)
  }
}

// 删除日程
const deleteEvent = async (id) => {
  try {
    // 确认删除
    if (confirm('确定要删除这个日程吗？')) {
      await scheduleApi.deleteSchedule(id)
      loadSchedules()
    }
  } catch (error) {
    console.error('删除日程失败:', error)
  }
}

// 日期变更
const changeDate = (e) => {
  currentDate.value = e.detail.value
  loadSchedules()
}

// 打开添加对话框
const showAddEventDialog = () => {
  isEdit.value = false
  selectedScheduleId.value = null
  eventForm.value = {
    title: '',
    date: currentDate.value,
    time: '09:00',
    description: '',
    type: 'work',
    points: 10
  }
  showAddDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false
}

// 表单输入变更
const onInputChange = (e) => {
  const { field } = e.currentTarget.dataset
  eventForm.value[field] = e.detail.value
}

// 日期选择
const onDateChange = (e) => {
  eventForm.value.date = e.detail.value
}

// 时间选择
const onTimeChange = (e) => {
  eventForm.value.time = e.detail.value
}

// 类型选择
const onTypeChange = (e) => {
  const index = e.detail.value
  eventForm.value.type = typeOptions[index].value
}

// 积分选择
const onPointsChange = (e) => {
  const index = e.detail.value
  eventForm.value.points = pointsOptions[index]
}

// 更新时间字符串
const updateTimeString = () => {
  if (eventForm.value.timeValue) {
    const hours = String(eventForm.value.timeValue.getHours()).padStart(2, '0')
    const minutes = String(eventForm.value.timeValue.getMinutes()).padStart(2, '0')
    eventForm.value.time = `${hours}:${minutes}`
  }
}

// 监听日期变化
watch(currentDate, (newVal) => {
  console.log('日期变更为:', formatDate(newVal, 'display'))
})
</script>

<style scoped>
.schedule-container {
  padding: 20px;
  background-color: #f9fbff;
  min-height: 100%;
}

.schedule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.schedule-header h3 {
  color: #1e5eff;
  font-size: 1.5rem;
}

.calendar-cell {
  position: relative;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.event-dot {
  position: absolute;
  bottom: 2px;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #1e5eff;
}

.events-list {
  padding: 0 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.events-list h4 {
  color: #1e5eff;
  margin-bottom: 20px;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-timeline {
  margin-top: 20px;
}

.el-card {
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-button--primary) {
  background-color: #1e5eff;
}

:deep(.el-calendar-day) {
  height: 40px;
  padding: 4px;
  text-align: center;
}

:deep(.el-calendar-table .el-calendar-day.is-selected) {
  background-color: #e6f1ff;
}

:deep(.el-timeline-item__node--primary) {
  background-color: #1e5eff;
}

:deep(.el-timeline-item__node--success) {
  background-color: #67c23a;
}

:deep(.el-timeline-item__node--danger) {
  background-color: #f56c6c;
}

:deep(.el-timeline-item__node--info) {
  background-color: #909399;
}
</style> 